<template>
    <van-nav-bar title="登录"/>
    <van-tabs v-model:active="active">
        <van-tab title="密码登录">
            <van-form required="auto" @submit="submitPasswordLogin">
                <van-field v-model="phone" :rules="phoneRules" label="手机号" placeholder="请输入手机号" />
                <van-field v-model="password" :rules="passwordRules" label="密码" placeholder="请输入密码" />
                <br>
                <van-button round block type="primary" native-type="submit"
                    style="width: 80%;margin-left: 10%;">登录</van-button>
            </van-form>
        </van-tab>
        <van-tab title="验证码登录">
            <van-form required="auto" @submit="submitCodeLogin">
                <van-field v-model="phone" :rules="phoneRules" label="手机号" placeholder="请输入手机号" />
                <van-field v-model="code" :rules="codeRules" center clearable label="短信验证码" placeholder="请输入短信验证码">
                    <template #button>
                        <van-button size="small" type="primary" @click="sendCode">发送验证码</van-button>
                    </template>
                </van-field>
                <br>
                <van-button round block type="primary" native-type="submit"
                    style="width: 80%;margin-left: 10%;">登录</van-button>
            </van-form>
        </van-tab>
    </van-tabs>
    <van-sticky :offset-bottom="50" position="bottom">
        <a href="#" @click.prevent="openDingding"><img src="../../assets/sf/钉钉.png" width="10%"></a>
    </van-sticky>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue';
import http from '../../http';
import { showToast } from 'vant';

// 定义输入框的 ref
const username = ref('');
const password = ref('');
const phone = ref('');
const code = ref('');
const urls = reactive({
    dingding: ''
});

// 定义 active 用于切换登录方式
const active = ref(0);

// 定义正则表达式
const passwordReg = /^[A-Za-z\d]{8,20}$/;
const phoneReg = /^1[3-9]\d{9}$/; // 手机号：以 1 开头，第二位为 3-9，共 11 位
const codeReg = /^\d{4}$/; // 验证码：6 位数字

// 定义输入框的验证规则
const passwordRules = [
    { required: true, message: '请输入密码' },
    { pattern: passwordReg, message: '密码格式错误，应为 8-20 位' }
];
const phoneRules = [
    { required: true, message: '请输入手机号' },
    { pattern: phoneReg, message: '手机号格式错误' }
];
const codeRules = [
    { required: true, message: '请输入验证码' },
    { pattern: codeReg, message: '验证码应为 4 位数字' }
];

// 点击左侧返回按钮
const onClickLeft = () => history.back();

// 发送验证码
const sendCode = async () => {
    if (!phoneReg.test(phone.value)) {
        showToast('请输入正确的手机号');
        return;
    }
    try {
        http.get('user/send/?phone=' + phone.value).then(res => {
            if (res.data.code === 200) {
                alert(res.data.data);
                showToast('验证码已发送');
            } else {
                showToast('验证码发送失败，请重试');
            }
        })
    } catch (error) {
        showToast('发送验证码失败，请重试');
        console.error('Error:', error);
    }
};

// 密码登录
const submitPasswordLogin = async (event) => {
    try {
        http.post('user/paswordlogin/', {
            phone: phone.value,
            password: password.value
        }).then(res => {
            if (res.data.code === 200) {
                showToast('登录成功');
                localStorage.setItem('token', res.data.data.token);
                localStorage.setItem('retoken', res.data.data.retoke);
                localStorage.setItem('userid', res.data.data.userid);
                window.location.href = '/';
            } else {
                showToast('登录失败，请重试');
            }
        })
    } catch (error) {
        showToast('登录失败，请重试');
        console.error('Error:', error);
    }
};

// 验证码登录
const submitCodeLogin = async (event) => {
    try {
        http.post('user/codelogin/', {
            phone: phone.value,
            code: code.value
        }).then(res => {
            if (res.data.code === 200) {
                showToast('登录成功');
                localStorage.setItem('token', res.data.data.token);
                localStorage.setItem('retoken', res.data.data.retoken);
                localStorage.setItem('userid', res.data.data.userid);
                window.location.href = '/';
            } else {
                showToast('登录失败，请重试');
            }
        })
    } catch (error) {
        showToast('登录失败，请重试');
        console.error('Error:', error);
    }
};

// 打开钉钉登录
const openDingding = () => {
    http.post('user/dinglogin/', {
        types: 'dingding'
    }).then(res => {
        urls.dingding = res.data.url;
        window.open(urls.dingding, '_blank');
    })
        .catch(error => {
            showToast('打开钉钉登录失败，请重试');
            console.error('Error:', error);
        });
};

onMounted(() => {
    if (localStorage.getItem('userid')) {
        showToast('已登录');
        window.location.href = '/';
    }
})
</script>

<style scoped></style>